const { saveUserInfo } = require('../../utils/user.js')
const { getApiUrl } = require('../../config/config.js')
Page({
  data: {
    studentId: '',
    email: '',
    verifyCode: '',
    password: '',
    confirmPassword: '',
    showPassword: false,
    showConfirmPassword: false,
    isAgree: false,
    canSendCode: true,
    countdown: 0,
    passwordFocus: false,
    confirmPasswordFocus: false,
    passwordStrength: 0,
    strengthText: '',
    showSuccessModal: false
  },

  onLoad() {
    // 尝试恢复表单数据
    const formData = wx.getStorageSync('registerFormData')
    if (formData) {
      this.setData(formData)
    }
  },

  // 保存表单数据
  saveFormData() {
    const formData = {
      studentId: this.data.studentId,
      email: this.data.email,
      verifyCode: this.data.verifyCode,
      password: this.data.password,
      confirmPassword: this.data.confirmPassword,
      isAgree: this.data.isAgree
    }
    wx.setStorageSync('registerFormData', formData)
  },

  // 输入事件处理
  onStudentIdInput(e) {
    this.setData({ studentId: e.detail.value })
  },

  onEmailInput(e) {
    const email = e.detail.value
    // 验证邮箱格式
    const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    this.setData({ 
      email,
      canSendCode: emailRegex.test(email)
    })
  },

  onVerifyCodeInput(e) {
    this.setData({ verifyCode: e.detail.value })
  },

  onPasswordInput(e) {
    const password = e.detail.value;
    this.setData({ password });
    this.checkPasswordStrength(password);
  },

  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value })
  },

  // 切换密码可见性
  togglePasswordVisibility() {
    this.setData({ showPassword: !this.data.showPassword })
  },

  toggleConfirmPasswordVisibility() {
    this.setData({ showConfirmPassword: !this.data.showConfirmPassword })
  },

  // 发送验证码
  async onTapSendCode() {
    if (!this.data.canSendCode) return
    
    // 验证邮箱格式
    const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (!emailRegex.test(this.data.email)) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({
        title: '发送中...'
      })
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/captcha'),
          method: 'POST',
          data: {
            email: this.data.email
          },
          timeout: 120000, // 将超时时间设置为120秒
          success: resolve,
          fail: (err) => {
            if (err.errMsg.includes('timeout')) {
              reject(new Error('请求超时，请检查网络后重试'))
            } else {
              reject(err)
            }
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      })

      if (res.data) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        // 开始倒计时
        this.setData({
          canSendCode: false,
          countdown: 60
        })

        this.countdownTimer = setInterval(() => {
          if (this.data.countdown <= 1) {
            clearInterval(this.countdownTimer)
            this.setData({
              canSendCode: true,
              countdown: 0
            })
          } else {
            this.setData({
              countdown: this.data.countdown - 1
            })
          }
        }, 1000)
      } else {
        throw new Error(res.data.message || '发送失败')
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '发送失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 同意协议
  onAgreeChange(e) {
    this.setData({ isAgree: e.detail.value.length > 0 })
  },

  // 查看协议
  onTapAgreement() {
    // 保存当前表单数据
    this.saveFormData()
    wx.navigateTo({
      url: '/pages/agreement/agreement'
    })
  },

  // 检查密码强度
  checkPasswordStrength(password) {
    let strength = 0;
    const hasLetter = /[a-zA-Z]/.test(password);
    const hasNumber = /[0-9]/.test(password);
    const hasSpecial = /[!@#$%^&*]/.test(password);
    
    if (password.length < 8) {
      strength = 1;
    } else if (hasLetter && hasNumber && hasSpecial) {
      strength = 3;
    } else if ((hasLetter && hasNumber) || (hasLetter && hasSpecial) || (hasNumber && hasSpecial)) {
      strength = 2;
    } else {
      strength = 1;
    }

    const strengthTexts = ['弱', '中', '强'];
    
    this.setData({
      passwordStrength: strength,
      strengthText: strengthTexts[strength - 1]
    });
  },

  onPasswordFocus() {
    this.setData({ passwordFocus: true });
  },

  onPasswordBlur() {
    this.setData({ passwordFocus: false });
  },

  onConfirmPasswordFocus() {
    this.setData({ confirmPasswordFocus: true });
  },

  onConfirmPasswordBlur() {
    this.setData({ confirmPasswordFocus: false });
  },

  // 注册
  async onTapRegister() {
    const { studentId, email, verifyCode, password, confirmPassword, isAgree } = this.data

    // 验证表单
    if (!studentId) {
      wx.showToast({
        title: '请输入学号/工号',
        icon: 'none'
      })
      return
    }

    if (!email || !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      })
      return
    }

    if (!verifyCode) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }

    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }

    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      })
      return
    }

    if (!isAgree) {
      wx.showToast({
        title: '请同意用户协议',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '注册中...'
    })

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/user/register'),
          method: 'POST',
          data: {
            userAccount: studentId,
            userPassword: password,
            checkPassword: confirmPassword,
            email: email,
            captcha: verifyCode
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }, 1500)
      } else {
        throw new Error(res.data.message || '注册失败')
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '注册失败，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 开始使用
  onTapStart() {
    // 清除表单数据
    wx.removeStorageSync('registerFormData')
    // 跳转到首页
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  onShow() {
    // 检查是否已同意协议
    const hasAgreed = wx.getStorageSync('hasAgreedToTerms')
    if (hasAgreed) {
      this.setData({
        isAgree: true
      })
    }
  },

  // 跳转到登录页面
  onTapLogin() {
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  // 页面卸载时清除存储的表单数据
  onUnload() {
    // 只有在注册成功时才清除表单数据
    if (this.data.showSuccessModal) {
      wx.removeStorageSync('registerFormData')
    }
  }
}) 